import { postLoginAPI, postLoginWxMinAPI, postLoginWxMinSimpleAPI } from '@/services/login'
import { useMemberStore } from '@/stores'
import type { LoginResult } from '@/types/member'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

const useLoginHooks = () => {
  // #ifdef MP-WEIXIN
  // 获取 code 登录凭证
  let code = ''

  // 获取用户手机号码
  const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
    const { encryptedData, iv } = ev.detail
    const res = await postLoginWxMinAPI({ code, encryptedData, iv })
    loginSuccess(res.result)
  }
  // #endif

  // 模拟手机号码快捷登录（开发练习）
  const onGetphonenumberSimple = async () => {
    const res = await postLoginWxMinSimpleAPI('13123456789')
    loginSuccess(res.result)
  }

  const loginSuccess = (profile: LoginResult) => {
    // 保存会员信息
    const memberStore = useMemberStore()
    memberStore.setProfile(profile)
    // 成功提示
    uni.showToast({ icon: 'success', title: '登录成功' })
    setTimeout(() => {
      // 页面跳转
      // uni.switchTab({ url: '/pages/my/my' })
      uni.navigateBack()
    }, 500)
  }

  // 传统表单登录，测试账号：13123456789 密码：123456，测试账号仅开发学习使用。
  const form = ref({
    account: '13123456789',
    password: '',
  })

  // 表单提交
  const onSubmit = async () => {
    const res = await postLoginAPI(form.value)
    loginSuccess(res.result)
  }

  onLoad(async () => {
    const res = await wx.login()
    code = res.code
  })

  return {
    form,
    onSubmit,
    onGetphonenumber,
    onGetphonenumberSimple,
  }
}

export default useLoginHooks
